package com.example.myapplication3;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class RateActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "RateActivity";
    private TextView out;
    private EditText inp;
    float dollarRate = 0.1528f;
    float poundRate = 0.1113f;
    float euroRate = 0.1284f;
    Handler handler;


    public void click(View v) {
        Log.d(TAG, "click:");
        float r = 0.0f;
        switch (v.getId()) {
            case R.id.btn_dollar:
                r = dollarRate;    //r=0.1528f;删掉上面的float dollarRate
                break;
            case R.id.btn_pound:
                r = poundRate;    //r=0.1113f;
                break;
            case R.id.btn_euro:
                r = euroRate;     //r=0.1284f;
                break;
        }
        String str = inp.getText().toString();
        Log.i(TAG, "click:str" + str);
        if (str == null || str.length() == 0) {
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
        } else {
            r = r * Float.parseFloat(str);
            out.setText(String.valueOf(r));
        }
    }

    protected void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_rate);
        out = findViewById(R.id.textView2);
        inp = findViewById(R.id.editTextTextnumber);
        // 获得对象
        SharedPreferences sharePreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        //  这个和上面的一句选其中一句PreferenceManager.getDefaultSharedPreferences(this);
        // 获取保存在数据中的数据
        dollarRate = sharePreferences.getFloat("dollarRate", 0.0f);
        poundRate = sharePreferences.getFloat("poundRate", 0.0f);
        euroRate = sharePreferences.getFloat("euroRate", 0.0f);
        //获取数据，保存到myrate.xml文件，在device file explorer-data-data-example.myapplication3-shared-myrate.xml
        Thread t = new Thread(this);
        t.start();

        handler = new Handler() {
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 7) {
                    String str = (String) msg.obj;
                    Log.i(TAG, "handleMessage:get str=" + str);
                    out.setText(str);
                }
                super.handleMessage(msg);
            }
        };
    }

    public void clickconfig(View v1) {
        Log.i(TAG, "clickconfig:...");
        open();
    }

    private void open() {
        Intent config = new Intent(this, SaveActivity.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("pound_rate_key", poundRate);
        config.putExtra("euro_rate_key", euroRate);
        Log.i(TAG, "clickconfig:dollarRate" + dollarRate);
        Log.i(TAG, "clickconfig:poundRate" + poundRate);
        Log.i(TAG, "clickconfig:euroRate" + euroRate);

        //startActivity(config);
        startActivityForResult(config, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == 2) {
            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar", 0.1f);
            poundRate = bundle.getFloat("key_pound", 0.1f);
            euroRate = bundle.getFloat("key_euro", 0.1f);
            Log.i(TAG, "onActivityResult:dollarRate" + dollarRate);
            Log.i(TAG, "onActivityResult:poundRate" + poundRate);
            Log.i(TAG, "onActivityResult:euroRate" + euroRate);
        }
        super.onActivityResult(requestCode, resultCode, data);

        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat("dollar_rate", dollarRate);
        editor.putFloat("pound_rate", poundRate);
        editor.putFloat("euro_rate", euroRate);
 //        1//一天更新一次新添这两句
 //        1String todayStr = null;
 //        1editor.putString("update_date",todayStr);
        editor.apply();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_setting) {
            open();
        }
        return super.onOptionsItemSelected(item);
    }

    public void run() {
        Log.i(TAG, "run:........");

        //下面这一段直接输入Thread.sleep(3000);，报错点击跳出catch
        try {
            Thread.sleep(3000); //加了延时并不是必要的
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //线程中完成的任务。。。。。
        // URL url = null;
        List<String> ret=new ArrayList<String>();
        try {
//            URL url = new URL("https://qq.ip138.com/hl.asp");
//            HttpURLConnection http = (HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//            String html = inputStream2String(in);
//            Log.i(TAG, "run:html:" + html);
 //            1//获取系统当前时间
 //            1Date date = Calendar.getInstance().getTime();
 //            1SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-M-dd");
 //            1todayStr = simpleDateFormat.format(date);
 //            1Log.i(TAG, "run: todayStr系统当前时间"+todayStr);

            Document doc= Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG,"run:title="+doc.title());
            //获取时间
            //body>section>v>div>article>p
 //            1//获取网页时间
 //            1Element publictime = doc.getElementsByClass("time").first();
 //            1Log.i(TAG, "run: title:"+publictime.text());//title:中行外汇牌价表更新时间:2021-4-27 14:00:57
 //            1String time = updatetime.substring(updatetime.indexOf(":")+ 1);
 //            1String updatetime = publictime.text().substring(12, 21);
 //            1Log.i(TAG, "run: title:"+updatetime);//run: title:2021-4-27

            Element publicTime=doc.getElementsByClass("time").first();
            Log.i(TAG,"run:time="+publicTime.html());
            Element table=doc.getElementsByTag("table").first();
            Elements trs=table.getElementsByTag("tr");   //Elements集合，Element单个
            for(Element tr:trs){
                Elements tds=tr.getElementsByTag("td");
                if(tds.size()>0){
                   Log.i(TAG,"run td="+tds.first().text());
                   Log.i(TAG,"run rate="+tds.get(5).text());
                   //将获取数据传到列表中去
                    String str=tds.first().text();
                    Log.i(TAG,"run:td="+str);
                   String val=tds.get(5).text();
                   Log.i(TAG,"run:rate="+val);
                   ret.add(str+"-->"+val);

                   if(tds.first().text().equals("美元")){
          //       Log.i(TAG,"run rate1="+tds.get(5).text());
                       String rate1=tds.get(5).text();
                       Log.i(TAG,"run rate1="+rate1);
                       float dollarr=100f/Float.parseFloat(rate1);
                       dollarRate=dollarr;
                   }
                    if(tds.first().text().equals("英镑")){
                        //       Log.i(TAG,"run rate1="+tds.get(5).text());
                        String rate2=tds.get(5).text();
                        Log.i(TAG,"run rate2="+rate2);
                        float poundr=100f/Float.parseFloat(rate2);
                        poundRate=poundr;
                    }
                    if(tds.first().text().equals("欧元")){
                        //       Log.i(TAG,"run rate1="+tds.get(5).text());
                        String rate3=tds.get(5).text();
                        Log.i(TAG,"run rate3="+rate3);
                        float euror=100f/Float.parseFloat(rate3);
                        euroRate=euror;
                    }
                }
            }
//            Element tr1=table.getElementsByTag("tr").get(28);
//            Log.i(TAG,"run tr1="+tr1);
//            Elements tds=tr1.getElementsByTag("td");
//            String rate1=tds.get(5).text();
//            Log.i(TAG,"run rate1="+rate1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回数据给主线程

        Message msg = handler.obtainMessage(7);
        msg.obj = "from message";
        handler.sendMessage(msg);

        //
    }

    private String inputStream2String(InputStream inputStream)
            throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "utf-8");  //gb2312或utf-8是根据网页来的
        while (true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
            return out.toString();
        }
        return null;   //这个是报错自动加上去的
    }

}
